﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.DirectoryServices;
using System.Drawing;
using System.Media;
using System.Text;
using System.Windows.Forms;

namespace UserAuthentication
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }

        private void buttonClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void buttonCheck_Click(object sender, EventArgs e)
        {
            string strDomain = textBoxDomain.Text.Trim();
            string strUserName = textBoxUserName.Text.Trim();
            string strPassword = textBoxPassword.Text.Trim();
            string strComments = string.Empty;
            bool boolValid = false;
            bool UserExist = false;

            if (checkBoxUserNameOnly.Checked == false)
            {
                boolValid = validatePassword(strDomain, strUserName, strPassword, out UserExist, out strComments);
            }
            else
            {
                boolValid = validateUserLogin(strDomain, strUserName, out strComments);
            }

            textBoxLog.Text = DateTime.Now.ToString("hh:mm:ss") + string.Format(@" - {0}\{1} - ", strDomain, strUserName) + strComments + Environment.NewLine + textBoxLog.Text;
            textBoxPassword.Focus();
        }

        public bool validateUserLogin(string stradDomain, string adUserName, out string strComments)
        {
            Cursor currentCursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
            string strEntry = @"LDAP://" + stradDomain;
            DirectoryEntry objDirectoryEntry = null;
            DirectorySearcher objDirectorySearcher = null;

            try
            {
                objDirectoryEntry = new DirectoryEntry(strEntry);
                objDirectorySearcher = new DirectorySearcher(objDirectoryEntry);
                objDirectorySearcher.Filter = "sAMAccountName=" + adUserName;
                objDirectorySearcher.SearchScope = SearchScope.Subtree;
                objDirectorySearcher.PropertiesToLoad.Add("cn");

                SearchResult myresult = objDirectorySearcher.FindOne();
                if (myresult == null)
                {
                    strComments = string.Format("user doesn't exist or current user({0}) doesn't have rights to browse AD", Environment.UserName);
                    return false;
                }
                else
                {
                    strComments = "user exist";
                    return true;
                }
            }
            catch (Exception ex)
            {
                strComments = string.Format("exception message - {0}", ex.Message);
                return false;
            }
            finally
            {
                Cursor.Current = currentCursor;
            }
        }

        public bool validatePassword(string stradDomain, string adUserName, string adPassword, out bool UserExist, out string strComments)
        {
            if (validateUserLogin(stradDomain, adUserName, out strComments) == false)
            {
                UserExist = false;
            }
            else
            {
                UserExist = true;
            }

            DirectoryEntry de = new DirectoryEntry(null, stradDomain + @"\" + adUserName, adPassword);
            Cursor currentCursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;

            try
            {
                object o = de.NativeObject;
                DirectorySearcher ds = new DirectorySearcher(de);
                ds.Filter = "samaccountname=" + adUserName;
                ds.PropertiesToLoad.Add("cn");
                SearchResult sr = ds.FindOne();
                if (sr == null)
                {
                    throw new Exception();
                }

                UserExist = true;
                strComments = "valid password";
                return true;
            }
            catch
            {
                strComments = "invalid password";
                return false;
            }
            finally
            {
                Cursor.Current = currentCursor;
            }
        }

        private void buttonClearLog_Click(object sender, EventArgs e)
        {
            textBoxLog.Text = string.Empty;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            textBoxDomain.Text = Environment.UserDomainName;

            textBoxUserName.Focus();
        }

        private void textBoxPassword_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                buttonCheck_Click(null, null);
            }
        }

        private void checkBoxUserNameOnly_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxUserNameOnly.Checked == true)
            {
                textBoxPassword.Text = string.Empty;
                textBoxPassword.Enabled = false;
            }
            else
            {
                textBoxPassword.Enabled = true;
            }
        }

        private void textBoxUserName_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                buttonCheck_Click(null, null);
            }
        }

        //private void buttonReset_Click(object sender, EventArgs e)
        //{
        //    string strDomain = textBoxDomain.Text.Trim();
        //    string strUserName = textBoxUserName.Text.Trim();

        //    ResetPassword objResetPassword = new ResetPassword();
        //    objResetPassword.setUserAccount(string.Format(@"{0}\{1}", strDomain, strUserName));
        //    objResetPassword.ShowDialog(this);
        //}

        private void buttonChangePassword_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBoxDomain.Text.Trim()) || string.IsNullOrEmpty(textBoxUserName.Text.Trim()))
            {
                MessageBox.Show("Please enter user login name first!");
                textBoxUserName.Focus();

                return;
            }

            ChangePassword formChangePassword = new ChangePassword();
            formChangePassword.StartPosition = FormStartPosition.CenterParent;
            formChangePassword.SetUserName(textBoxDomain.Text.Trim(), textBoxUserName.Text.Trim());
            formChangePassword.SetOldPassword(textBoxPassword.Text);
            formChangePassword.ShowDialog(this);
        }
    }
}
